package com.heima.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.api.mapper.ApArticleMapper;
import com.heima.api.service.HotArticleService;
import com.heima.api.wemedia.IWemediaClient;
import com.heima.common.contants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Transactional
@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 定时计算热点文章
     */
    @Override
    public void computeHotArticle() {

        //查询前5天发布的文章
        Date dateParam = DateTime.now().minusDays(500).toDate();
        List<ApArticle> apArticleList = apArticleMapper.findArticleListByDays(dateParam);

        //计算文章分值
        List<HotArticleVo> hotArticleList = computeHotArticle(apArticleList);

        //给每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleList);
    }

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 给每个频道缓存30条分值较高的文章
     * @param hotArticleList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleList) {
        //查询所有频道
        ResponseResult responseResult = wemediaClient.getChannels();
        if(responseResult.getCode().equals(200)){
            //转换数据
            List<WmChannel> wmChannels = JSON.parseArray(JSON.toJSONString(responseResult.getData()), WmChannel.class);
            for (WmChannel wmChannel : wmChannels) {
                //检索出对应频道的文章列表
                List<HotArticleVo> hotArticleVos = hotArticleList.stream()
                        .filter(x -> x.getChannelId().equals(wmChannel.getId()))//过滤，检索出文章对应当前频道的数据
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())//按照分值进行倒序排序
                        .limit(30)//取出30条数据
                        .collect(Collectors.toList());
                //排序，取30条，存入redis
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+wmChannel.getId(), JSON.toJSONString(hotArticleVos));

            }
        }

        //给推荐频道设置缓存
        hotArticleList = hotArticleList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG, JSON.toJSONString(hotArticleList));


    }

    /**
     * 计算文章分值
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticleList) {

        List<HotArticleVo> hotArticleVoList = new ArrayList<>();

        if(apArticleList != null && apArticleList.size() > 0){
            for (ApArticle apArticle : apArticleList) {
                HotArticleVo hot = new HotArticleVo();
                //属性拷贝
                BeanUtils.copyProperties(apArticle,hot);
                //计算文章具体分值
                Integer score = computeScore(apArticle);
                hot.setScore(score);
                hotArticleVoList.add(hot);

            }
        }
        return hotArticleVoList;
    }

    /**
     * 计算文章具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;

        if(apArticle.getLikes() != null){
            score += apArticle.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }

        if(apArticle.getComment() != null){
            score += apArticle.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        if(apArticle.getCollection() != null){
            score += apArticle.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}